#pragma once

#include <iostream>
#include <vector>
#include <unistd.h>
#include <cstdlib>
#include <string>
#include <sys/wait.h>
#include <cstdio>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#define PATH "."
#define FIFO "fifo"

class NameFifo
{
public:
    NameFifo(const char *path = PATH, const char *name = FIFO) : _path(path), _name(name), _fd(-1)
    {
        _fifoname = _path + "/" + _name;
        //std::cout << _fifoname << std::endl;
    }
    void Create()
    {
        umask(0);
        int n = mkfifo(_fifoname.c_str(), 0666);
        //std::cout<< _fifoname << std ::endl;
        if (n < 0)
        {
            perror("mkfifo");
            return;
        }
    }
    void OpenORDONLY()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            perror("open");
            exit(1);
        }
        std::cout << "Open Success! " << std::endl;
    }
    void OpenOWRONLY()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            perror("open");
            exit(1);
        }
        std::cout << "Open Success! " << std::endl;
    }
    void Close()
    {
        if (_fd >= 0)
            close(_fd);
    }
    void Stop()
    {
        unlink(_fifoname.c_str());
    }
    void Read()
    {
        while (true)
        {
            char buffer[1024];
            ssize_t s = read(_fd, buffer, sizeof(buffer) - 1);
            if (s > 0)
            {
                buffer[s] = 0;
                std::cout << "Client Say#: " << buffer << std::endl;
            }
            else if (s == 0)
            {
                std::cout << "Client Quit" << std::endl;
                break;
            }
            else
            {
                std::cout << "read error" << std::endl;
                break;
            }
        }
    }
    void Write()
    {
        while (true)
        {
            //std::cout << _fifoname << " " << _fd  << std::endl;
            std::cout << "input->:";
            std::string message;
            std::getline(std::cin, message);
            write(_fd, message.c_str(), message.size());
        }
    }

    ~NameFifo()
    {

    }

private:
    std::string _path;
    std::string _name;
    int _fd;
    std::string _fifoname;
};